// src/api/flow-api.ts
import request from '@/utils/request'
import type { FlowAPI } from '@/types/types'

export const saveFlow = (data: any) => {
    return request.post('/flow/save', data)
}

export const deleteFlow = (data: any) => {
    return request.post('/flow/delete', data)
}

export const runFlow = (data: any) => {
    return request.post('/flow/run', data)
}

export const getFlowList = () => {
    return request.get('/flow/list')
}

export const getFlow = (data: any) => {
    return request.post('/flow/get', data)
}

export const sendStreamMessage = async (data: any) => {
    const stream = await request.postStream('/flow/message', data)

    if (!stream || !(stream instanceof ReadableStream)) {
        throw new Error('Failed to get readable stream')
    }
    return stream
}


export const parseSSE = (chunk: string): any[] => {
    const results = [];
    const lines = chunk.split(/\r?\n/); // 支持 \n 或 \r\n 换行
    let buffer = '';

    for (const line of lines) {
        if (line.startsWith('data:')) {
            let jsonStr = line.slice(5).trim(); // 去掉 "data:" 和前后空格

            if (!jsonStr) continue;

            buffer += jsonStr;
        } else if (line.trim() === '') {
            // 空行表示一个完整的事件结束，尝试解析
            if (buffer) {
                try {
                    const parsed = JSON.parse(buffer);

                    // 如果 message 是 base64 字符串，进行解码
                    if (typeof parsed.message === 'string') {
                        try {
                            // 使用 atob 解码（浏览器环境）
                            parsed.message = decodeURIComponent(
                                atob(parsed.message)
                                    .split('')
                                    .map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
                                    .join('')
                            );
                        } catch (e) {
                            console.warn('Base64 解码失败:', parsed.message, e);
                        }
                    }

                    results.push(parsed);
                    buffer = ''; // 清空缓冲区
                } catch (e) {
                    console.warn('JSON 解析失败:', buffer, e);
                    buffer = ''; // 解析失败也清空
                }
            }
        } else {
            continue;
        }
    }

    // 如果 buffer 中还有未完成的数据，保留到下一次调用
    if (buffer) {
        console.warn('部分数据未完成，已缓存:', buffer);
    }

    return results;
};

export const addModel = (data: any) => {
    return request.post('/model/save', data)
}

export const deleteModel = (data: any) => {
    return request.post('/model/delete', data)
}

export const getModelList = () => {
    return request.get('/model/list')
}

export const getModel = (data: any) => {
    return request.post('/model/get', data)
}

export const getModelNames = (data: any) => {
    return request.post('/model/chatmodel/list', data)
}


export const addMcp = (data: any) => {
    return request.post('/mcp/save', data)
}

export const deleteMcp = (data: any) => {
    return request.post('/mcp/delete', data)
}

export const getMcpList = () => {
    return request.get('/mcp/list')
}

export const getMcp = (data: any) => {
    return request.post('/mcp/get', data)
}

export const getMcpCaps = (data: any) => {
    return request.post('/mcp/getCaps', data)
}


export const api: FlowAPI = {
    getFlow: (params) => getFlow(params),
    getFlowList: getFlowList,
    saveFlow: saveFlow,
    deleteFlow: deleteFlow,
    runFlow: runFlow,
    sendStreamMessage: sendStreamMessage,

    addModel: addModel,
    deleteModel: deleteModel,
    getModelList: getModelList,
    getModel: getModel,
    getModelNames: getModelNames,

    addMcp: addMcp,
    deleteMcp: deleteMcp,
    getMcpList: getMcpList,
    getMcp: getMcp,
    getMcpCaps: getMcpCaps
};